<?php

class FollowController
{
    private $userModel;
    private $followModel;
    private $autoUidModel;
    private $userMemberModel;
    private $userStatisticsModel;
    private $diaryListCacheModel;
    private $tokenUserCacheModel;
    private $followMeType       =   1;
    private $meFollowType       =   2;
    
    function __construct()/*{{{*/
    {
        $this->userModel            =   new UserModel();
        $this->followModel          =   new FollowModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->userMemberModel      =   new UserMemberModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
	    $this->tokenUserCacheModel  =   new TokenUserCacheModel();
    }/*}}}*/

    public function getFollowMeList($followInfo) {
        $followInfo['type'] = $this->followMeType;
        $result = $this->getFollowList($followInfo);
        $this->userStatisticsModel->resetNewFansStatistics($followInfo);
        return $result;
    }
    
    public function getMeFollowList($followInfo) {
        $followInfo['type'] = $this->meFollowType;
        $result = $this->getFollowList($followInfo);
        return $result;
    }
    
    private function getFollowList($followInfo) {
        $uid  = intval($followInfo['uid']);
        $type = intval($followInfo['type']);
        if (empty($uid)) return FALSE;

        list($id, $start, $length) = UK::assemblePageData($followInfo);

        $list = $this->followModel->getFollowList($id, $uid, $type, $start, $length);
        if (empty($list)) return array();
        
        $result = array();
        foreach ($list as $value) {
            $result[] = $this->followListData($value);
        }
        
        return $result;
    }
    
    public function meFollow($followInfo)/*{{{*/
    {
        if (empty($followInfo['uid'])   ||  empty($followInfo['fUid']))
        {
            AC::$errorNo    =   'FOC001';
            return  FALSE;
        }

        $userBaseInfo       =   $this->autoUidModel->getUserInfo($followInfo['uid']);
        if (!isset($userBaseInfo['nickname']))
        {
            AC::$errorNo    =   'FOC002';
            return  FALSE;
        }
        $meFollowLimit      =   $this->getMeFollowLimit($followInfo['uid']);
        if (empty($meFollowLimit))
        {
            return  FALSE;
        }

        $fUidBaseInfo       =   $this->autoUidModel->getUserInfo($followInfo['fUid']);
        if (!isset($fUidBaseInfo['nickname']))
        {
            AC::$errorNo    =   'FOC003';
            return  FALSE;
        }
        if ($fUidBaseInfo['is_vip'] && $fUidBaseInfo['vip_info']['follow_rule']==1){
            //会员，开启禁止关注
            AC::$errorNo = 'VIP004';//对方已开启高冷模式
            return FALSE;
        }

        $followInfo['nickname']     =   $userBaseInfo['nickname'];
        $followInfo['fNickname']    =   $fUidBaseInfo['nickname'];

        $result =   $this->followModel->meFollow($followInfo);
        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        // redis增加好友列表 并重新获取用户关注列表
        $this->diaryListCacheModel->addFriends($followInfo['uid'], $followInfo['fUid']);
        $this->diaryListCacheModel->addFans($followInfo['fUid'], $followInfo['uid']);
        if (!isset($followInfo['gmClose']) || empty($followInfo['gmClose'])){
            RedisPool::addGearmanJob("timeline", array("uid"=>$followInfo['uid']), $followInfo['uid']);
        }

        // 重建好友粉丝列表
        $this->autoUidModel->rebuildUserFollowersAndFansList($followInfo['uid']);
        $this->autoUidModel->rebuildUserFollowersAndFansList($followInfo['fUid']);
        
        // 计数及动态更新
        AC::$userStatistics[$followInfo['uid']]['meFollowTimes']    =   1;
        AC::$userStatistics[$followInfo['fUid']]['followMeTimes']   =   1;
        AC::$userStatistics[$followInfo['fUid']]['newFollowTimes']  =   0;
        AC::$userStatistics[$followInfo['fUid']]['newLikeMeTimes']  =   1;
        AC::$feedInfo   =   array(
                                'uid'               =>  $followInfo['uid'],
                                'eUid'              =>  $followInfo['uid'],
                                'eNickname'         =>  $followInfo['nickname'],
                                'authorUid'         =>  $followInfo['fUid'],
                                'authorNickname'    =>  $followInfo['fNickname'],
                                'type'              =>  AC::FEED_FOLLOW,
                                'content'           =>  'follow la~ follow la~!',
                            );
		
        // 推送
        $push	=	new PushController();
        $push->push($followInfo, "pushFollow");
        
        return  $result;
    }/*}}}*/
    
    /**
     * 一键关注
     * @param unknown $info
     * @return boolean
     */
    public function meFollowMany($info)/*{{{*/
    {
        $info['uid']     =    AC::HOST_UID;
        
        // handle params
        $fUidList        =    explode(',', trim($info['fUid'], ','));
        $meFollowList    =    $this->diaryListCacheModel->getFriendsList($info['uid']);
        if (count($meFollowList) > 0){
            return TRUE;
        }
        
        $uids            =    array_diff($fUidList, $meFollowList);
        if (empty($fUidList) || empty($uids)){
            return FALSE;
        }

        $num = 0;
        foreach ($uids as $fUid){
            $info['fUid']    = intval($fUid);
            $info['gmClose'] = TRUE;
            
            $this->meFollow($info);
            if (!empty(AC::$errorNo)){
                return FALSE;
                break;
            }
            AC::$userStatistics[$info['fUid']]['newLikeMeTimes']  =   0;
            $num++;
        }
        AC::$userStatistics[$info['uid']]['meFollowTimes']    =   $num;
        RedisPool::addGearmanJob("timeline", array("uid"=>$info['uid']), $info['uid']);
        return TRUE;
    }
    
    public function removeFollow($followInfo)/*{{{*/
    {
        if (empty($followInfo['type'])  ||  (1  !=  $followInfo['type']))
        {
            $result =   $this->followModel->removeFollow($followInfo);
            $this->diaryListCacheModel->delFriends($followInfo['uid'], $followInfo['fUid']);
        }
        else
        { // 屏蔽删除粉丝
            AC::$errorNo    =   'FOC099';
            return  FALSE;
            $this->diaryListCacheModel->delFriends($followInfo['fUid'], $followInfo['uid']);
            $result =   $this->followModel->removeFans($followInfo);
        }

        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        if (empty($followInfo['type'])  ||  (1  !=  $followInfo['type']))
        {
            AC::$userStatistics[$followInfo['uid']]['meFollowTimes']    =   -1;
            AC::$userStatistics[$followInfo['fUid']]['followMeTimes']   =   -1;

        }
        else
        {
            AC::$userStatistics[$followInfo['fUid']]['meFollowTimes']   =   -1;
            AC::$userStatistics[$followInfo['uid']]['followMeTimes']    =   -1;
            
        }

       	$fUserInfo = $this->autoUidModel->getUserInfo($followInfo['fUid']);
        if($fUserInfo && !empty($fUserInfo['is_vip'])){
            $userSettingModel = new UserSettingModel();
            $fUserSettingInfo = $userSettingModel->getSettingInfo($followInfo['fUid']);
            if(!empty($fUserSettingInfo) && $fUserSettingInfo['string3'] == '1') {
                $userInfo = $this->autoUidModel->getUserInfo($followInfo['uid']);
                $messageModel = new MessageBoxModel();
                $param = array(
                    'uid' => '8',
                    'mUid' => $fUserInfo['uid'],
                    'nickname' => '粉粉会员',
                    'mNickname' => $fUserInfo['nickname'],
                    'content' => '【会员功能-取关通知】你的好友 ' . $userInfo['nickname'] . ' 暂时取关了你。此时的暂别，是为了更好的相遇。',
                );
                $messageModel->sendAbilityMessage($param);
            }
		}
        // 重建时间线
        RedisPool::addGearmanJob("timeline", array("uid"=>$followInfo['uid']), $followInfo['uid']);
        
        return  $result;
    }/*}}}*/

    public function getBlacklist($followInfo)/*{{{*/
    {
       
        $result    =   $this->followModel->getMeBlacklist($followInfo);
        if (empty($result) || !is_array($result)){
            return array();
        }
        $result = $this->getBlackInfo($result,$followInfo['uid']);
        return  $result;
    }/*}}}*/
    
    /**
     * 获取黑名单列表,如果redis为空则从数据库获取
     * @param unknown $uids
     * @param unknown $followInfo
     * @return multitype:multitype:unknown NULL  Ambigous <unknown, multitype:Ambigous <NULL, multitype:unknown Ambigous <> > >
     */
    public function getBlackInfo($fUids,$uid){
        $blackList = array();
        foreach ($fUids as $fUid){
            $userInfo = $this->autoUidModel->getUserInfo($fUid);
            $black['uid']     =     $uid;
            $black['fUid']    =     $fUid;
            $black['type']    =     '2';
            $black['status']  =     '2';
            $black['userInfo']['uid']       =     $userInfo['uid'];
            $black['userInfo']['nickname']  =     $userInfo['nickname'];
            $black['userInfo']['signature'] =     $userInfo['signature'];
            $black['userInfo']['avatar']    =     $userInfo['avatar'];
            $black['userInfo']['is_vip']    =     $userInfo['is_vip'];
            $black['userInfo']['is_ability']=     $userInfo['is_ability'];
            $blackList[]      =    $black;
        }
        return $blackList;
    }
    
    public function blacklistFollow($followInfo)/*{{{*/
    {
        if (empty($followInfo['uid'])   ||  empty($followInfo['fUid']))
        {
            AC::$errorNo    =   'FOC004';
            return  FALSE;
        }

        $userBaseInfo       =   $this->autoUidModel->getUserInfo($followInfo['uid']);
        if (!isset($userBaseInfo['nickname']))
        {
            AC::$errorNo    =   'FOC005';
            return  FALSE;
        }

        $fUidBaseInfo       =   $this->autoUidModel->getUserInfo($followInfo['fUid']);
        if (!isset($fUidBaseInfo['nickname']))
        {
            AC::$errorNo    =   'FOC006';
            return  FALSE;
        }
        
        // 官方账号不能被拉黑
        if ($followInfo['fUid'] < 20){
            AC::$errorNo    =   'FOC010';
            AC::$errorMsg   =   '抱歉，'.$fUidBaseInfo['nickname'].'不能被列入黑名单';
            return  FALSE;
        }
         AC::$userStatistics[$followInfo['uid']]['meFollowTimes']    =  -1;
         AC::$userStatistics[$followInfo['fUid']]['followMeTimes']   =  -1;
         AC::$userStatistics[$followInfo['uid']]['meBlackTimes']     =   1;
         AC::$userStatistics[$followInfo['fUid']]['blackMeTimes']    =   1;
        $isCheckFollowInfo  =   $this->followModel->getFollowInfo($followInfo);
        if (empty($isCheckFollowInfo['meFollow'])   ||  (AC::FOLLOW_STATUS_NORMAL   !=  $isCheckFollowInfo['meFollow']['status']))
        {
            unset(AC::$userStatistics[$followInfo['uid']]['meFollowTimes']);
            unset(AC::$userStatistics[$followInfo['fUid']]['followMeTimes']);
        }

        $followInfo['nickname']     =   $userBaseInfo['nickname'];
        $followInfo['fNickname']    =   $fUidBaseInfo['nickname'];
        $result =   $this->followModel->blacklistFollow($followInfo);
        if (empty($result))
        {
            unset(AC::$userStatistics[$followInfo['uid']]['meFollowTimes']);
            unset(AC::$userStatistics[$followInfo['fUid']]['followMeTimes']);
            unset(AC::$userStatistics[$followInfo['uid']]['meBlackTimes']);
            unset(AC::$userStatistics[$followInfo['fUid']]['blackMeTimes']);
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        #redis删除好友
        $this->diaryListCacheModel->addBlackList($followInfo['uid'], $followInfo['fUid']);
        $this->diaryListCacheModel->delFriends($followInfo['uid'], $followInfo['fUid']);
        
        // 重建黑名单列表
        $this->rebuildUserBlackList($followInfo['uid']);
        $this->rebuildUserBlackList($followInfo['fUid']);
            
	//$this->autoUidModel->addBlacklistOfGearmanJob(array('uid' => $followInfo['uid'], 'fUid' => $followInfo['fUid']));
        return  $result;
    }/*}}}*/
    
    /**
     * 重建黑名单列表
     * @param unknown $uid
     * @return boolean
     */
    private function rebuildUserBlackList ($uid) {
        $this->userStatisticsModel->rebulidUserBlacked(array('uid' => $uid));
        return TRUE;
    }

    public function relieveBlacklist($followInfo)/*{{{*/
    {
        if (empty($followInfo['uid'])   ||  empty($followInfo['fUid']))
        {
            AC::$errorNo    =   'FOC007';
            return  FALSE;
        }
        $result =   $this->followModel->relieveBlacklist($followInfo);
        //删除redis中黑名单
        $this->diaryListCacheModel->delBlackList($followInfo['uid'], $followInfo['fUid']);
        
        
         AC::$userStatistics[$followInfo['uid']]['meBlackTimes']    =   -1;
         AC::$userStatistics[$followInfo['fUid']]['blackMeTimes']   =   -1;
        
        //$this->autoUidModel->addBlacklistOfGearmanJob(array('uid' => $followInfo['uid'], 'fUid' => $followInfo['fUid']), 'del');
        return  $result;
    }/*}}}*/

    private function getFollowUsereInfo($uid)/*{{{*/
    {
        $info   =   $this->autoUidModel->getUserInfo($uid);
        if (empty($info))   return  NULL;

        $info['nickname']    =    $this->autoUidModel->getRemarkName($info);
        return  $info;
    }/*}}}*/

    private function getMeFollowLimit($uid)/*{{{*/
    {
        $userStatistics     =   $this->userStatisticsModel->getUserStatistics(array('uid' => $uid));
        if (empty($userStatistics))
        {
            AC::$errorNo    =   'FOC008';
            return  FALSE;
        }
        $followLimitNumber  =   AC::FOLLOW_BASE_NUMBER;
        $userMemberInfo     =   $this->userMemberModel->getMemberInfo(array('uid' => $uid));
        if (!empty($userMemberInfo['level']))
        {
            if (!empty(ExpLevel::$levelMapFollow[$userMemberInfo['level']]))
            {
                $followLimitNumber  =   ExpLevel::$levelMapFollow[$userMemberInfo['level']];
            }
        }
        if ($userStatistics['meFollowTimes']    >   $followLimitNumber - 1)
        {
            AC::$errorNo    =   'FOC009';
            return  FALSE;
        }

        return  TRUE;
    }/*}}}*/
    
    private function followListData ($data) {
        $result = array(
            "id"    =>   "0",
            "uid"   =>   "0",
            "fUid"  =>   "0",
            "time"  =>   AC::SERVER_TIME,
            "type"  =>   "0",
            "status"=>   "0",
            "remark_name"   => "",
            "group_id"      => "0",
            "userInfo"      => (Object) array()
        );
    
        // 组装返回数据(不需要特殊处理,直接返回替换字段后的数据)
        UK::assembleReplacedFieldData($data, $result, array(
                'id'          =>    'id',
                'uid'         =>    'uid',
                'fUid'        =>    'fUid',
                'time'        =>    'time',
                'type'        =>    'type',
                'status'      =>    'status',
                'remark_name' =>    'remark_name',
                'group_id'    =>    'group_id'
            ));
    
        $result['userInfo']             = $this->autoUidModel->getUserInfo($result['fUid']);
        $result['remark_name'] = $result['userInfo']['nickname'] =    $this->autoUidModel->getRemarkName($result['userInfo']);
        return $result;
    }
    
}

